package net.suncaper.mvc.web.controller;

import lombok.var;
import net.suncaper.mvc.common.framework.simplemvc.RequestMapping;
import net.suncaper.mvc.common.utils.JSONUtil;
import net.suncaper.mvc.common.utils.Result;
import net.suncaper.mvc.model.domain.Hotel;
import net.suncaper.mvc.model.vo.HotelVO;
import net.suncaper.mvc.common.utils.EntityConverter;
import net.suncaper.mvc.exception.BusinessException;
import net.suncaper.mvc.service.IHotelService;
import net.suncaper.mvc.service.impl.HotelServiceImpl;
import net.suncaper.mvc.utils.AuthorizationUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;

/**
 * 酒店控制层
 */
@RequestMapping("/api/hotel")
public class HotelController {
    private IHotelService hotelService = new HotelServiceImpl();

    /**
     * 添加酒店
     */
    @RequestMapping("/add.do")
    public void addHotel(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            // 获取当前用户ID
            HttpSession session = request.getSession();
            String userId = (String) session.getAttribute("userId");
            if (userId == null) {
                JSONUtil.printByJSON(response, Result.error("用户未登录"));
                return;
            }
            
            // 检查用户权限
            AuthorizationUtil.requirePermission(userId, "create_hotel");
            
            String hotelName = request.getParameter("hotelName");
            String country = request.getParameter("country");
            String city = request.getParameter("city");
            String imageUrl = request.getParameter("imageUrl");
            BigDecimal longitude = BigDecimal.valueOf(Double.valueOf(request.getParameter("longitude")));
            BigDecimal latitude = BigDecimal.valueOf(Double.valueOf(request.getParameter("latitude")));
            
            // 检查酒店名是否已存在
            Hotel existingHotel = hotelService.getHotelByName(hotelName);
            if (existingHotel != null) {
                JSONUtil.printByJSON(response, Result.error("酒店名称已存在，请使用其他名称"));
                return;
            }

            Hotel hotel = new Hotel();
            hotel.setHotelName(hotelName);
            hotel.setCountry(country);
            hotel.setCity(city);
            hotel.setImageUrl(imageUrl);
            hotel.setLongitude(longitude);
            hotel.setLatitude(latitude);
            hotel.setRating(null); // 初始评分设为null，将由评价计算

            boolean result = hotelService.addHotel(hotel);
            JSONUtil.printByJSON(response, Result.success(result));
        } catch (BusinessException e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 根据名称获取酒店
     */
    @RequestMapping("/get.do")
    public void getHotelByName(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            // 获取当前用户ID
            HttpSession session = request.getSession();
            String userId = (String) session.getAttribute("userId");
            if (userId == null) {
                JSONUtil.printByJSON(response, Result.error("用户未登录"));
                return;
            }
            
            // 检查用户权限
            AuthorizationUtil.requirePermission(userId, "view_hotel");
            
            String hotelName = request.getParameter("hotelName");
            Hotel hotel = hotelService.getHotelByName(hotelName);
            if (hotel != null) {
                HotelVO hotelVO = EntityConverter.convertToHotelVO(hotel);
                JSONUtil.printByJSON(response, Result.success(hotelVO));
            } else {
                JSONUtil.printByJSON(response, Result.error("酒店不存在"));
            }
        } catch (BusinessException e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 根据位置筛选酒店
     */
    @RequestMapping("/listByLocation.do")
    public void listByLocation(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            // 获取当前用户ID
            HttpSession session = request.getSession();
            String userId = (String) session.getAttribute("userId");
            if (userId == null) {
                JSONUtil.printByJSON(response, Result.error("用户未登录"));
                return;
            }
            
            // 检查用户权限
            AuthorizationUtil.requirePermission(userId, "view_hotel");
            
            String country = request.getParameter("country");
            String city = request.getParameter("city");

            var hotels = hotelService.getHotelsByLocation(country, city);
            if (hotels != null) {
                java.util.List<HotelVO> hotelVOList = EntityConverter.convertToHotelVOList(hotels);
                JSONUtil.printByJSON(response, Result.success(hotelVOList));
            } else {
                JSONUtil.printByJSON(response, Result.success(new ArrayList<>()));
            }
        } catch (BusinessException e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }
    
    /**
     * 更新酒店信息
     */
    @RequestMapping("/update.do")
    public void updateHotel(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            // 获取当前用户ID
            HttpSession session = request.getSession();
            String userId = (String) session.getAttribute("userId");
            if (userId == null) {
                JSONUtil.printByJSON(response, Result.error("用户未登录"));
                return;
            }
            
            // 检查用户权限
            AuthorizationUtil.requirePermission(userId, "update_hotel");
            
            String hotelName = request.getParameter("hotelName");
            String country = request.getParameter("country");
            String city = request.getParameter("city");
            String imageUrl = request.getParameter("imageUrl");
            BigDecimal longitude = null;
            BigDecimal latitude = null;
            
            if (request.getParameter("longitude") != null && !request.getParameter("longitude").isEmpty()) {
                longitude = BigDecimal.valueOf(Double.valueOf(request.getParameter("longitude")));
            }
            
            if (request.getParameter("latitude") != null && !request.getParameter("latitude").isEmpty()) {
                latitude = BigDecimal.valueOf(Double.valueOf(request.getParameter("latitude")));
            }
            
            // 检查酒店是否存在
            Hotel existingHotel = hotelService.getHotelByName(hotelName);
            if (existingHotel == null) {
                JSONUtil.printByJSON(response, Result.error("要更新的酒店不存在"));
                return;
            }

            // 如果是酒店商家，需要检查是否是自己管理的酒店
            if (AuthorizationUtil.isHotelOwner(userId) && !AuthorizationUtil.isAdmin(userId)) {
                // 查询用户管理的酒店
                String userHotelName = hotelService.getHotelNameByUserId(userId);
                if (userHotelName == null || !userHotelName.equals(hotelName)) {
                    JSONUtil.printByJSON(response, Result.error("您只能修改自己管理的酒店信息"));
                    return;
                }
            }

            Hotel hotel = new Hotel();
            hotel.setHotelName(hotelName);
            hotel.setCountry(country);
            hotel.setCity(city);
            hotel.setImageUrl(imageUrl);
            hotel.setLongitude(longitude);
            hotel.setLatitude(latitude);
            hotel.setRating(existingHotel.getRating()); // 保留原有评分

            // 更新酒店信息
            boolean result = hotelService.updateHotel(hotel);
            
            JSONUtil.printByJSON(response, Result.success(result));
        } catch (BusinessException e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 查询全部酒店
     */
    @RequestMapping("/listAll.do")
    public void listAllHotels(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            java.util.List<Hotel> hotels = hotelService.getAllHotels();
            if (hotels != null) {
                java.util.List<HotelVO> hotelVOList = EntityConverter.convertToHotelVOList(hotels);
                JSONUtil.printByJSON(response, Result.success(hotelVOList));
            } else {
                JSONUtil.printByJSON(response, Result.success(new ArrayList<>()));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 删除酒店
     * 请求参数：hotelName
     */
    @RequestMapping("/delete.do")
    public void deleteHotel(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            String hotelName = request.getParameter("hotelName");
            boolean result = hotelService.deleteHotel(hotelName);
            JSONUtil.printByJSON(response, Result.success(result));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }

    /**
     * 根据用户ID获取酒店信息
     * 主要用于获取用户作为商家管理的酒店信息
     */
    @RequestMapping("/getByUserId.do")
    public void getHotelByUserId(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            
            // 获取请求参数
            String userId = request.getParameter("userId");
            if (userId == null || userId.trim().isEmpty()) {
                // 如果没有传入userId参数，则尝试从会话中获取当前用户ID
                HttpSession session = request.getSession();
                userId = (String) session.getAttribute("userId");
                if (userId == null) {
                    JSONUtil.printByJSON(response, Result.error("用户未登录或未提供用户ID"));
                    return;
                }
            }
            
            // 获取酒店信息
            Hotel hotel = hotelService.getHotelByUserId(userId);
            if (hotel != null) {
                HotelVO hotelVO = EntityConverter.convertToHotelVO(hotel);
                JSONUtil.printByJSON(response, Result.success(hotelVO));
            } else {
                JSONUtil.printByJSON(response, Result.error("该用户不是酒店商家或无关联酒店"));
            }
        } catch (BusinessException e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }
}    